// 添加请求拦截器
import axios from "axios";
import qs from "qs";
import cookin from "js-cookie";
import router from "@/router";
import NProgress from "nprogress"; //进度条样式
import { ElMessage } from "element-plus";
import store from "@/store";

let host = "";

//是否是开发版本和上线版本 开发环境
if (process.env.NODE_ENV === "development") {
  host = "/m.api";
} else {
  host = "http://192.168.1.188:8080";
}

let baseURL = host + "/m.api";
//创建实例对象
const instance = axios.create({});

//添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在发送请求做点什么
    NProgress.start();
    config.headers["AdminToken"] = cookin.get("token");
    return config;
  },
  (error) => {
    //对请求错误做些什么
    return Promise.reject(error);
  }
);
const requestType = ["_mt=create", "_mt=delete", "_mt=edit", "_mt=update"]; //当等于类型时进行无痛刷新
//添加响应拦截器
instance.interceptors.response.use(
  async function (response) {
    //async异步，结合await 使用
    // 对响应数据做点什么
    let { data } = response;
    let { errno, errmsg } = data;
    let path = router.currentRoute.value.fullPath;
    if (10006 === errno) {
      //未登录

      const configdata = response.config.data || "";
      var index = requestType.findIndex((item) => configdata.includes(item));
      console.log(index);
      if (-1 === index) {
        //需要重新获取令牌
        router.replace({ path: "/login", query: { back: path } });
        return;
      } else {
        //需要无痛刷新令牌
        const { username, password } = store.state.addusermodules.LoginData;
        //重新获取令牌
        let logindata = { _gp: "admin", _mt: "login", username, password }; //获取账号密码
        const { errno, errmsg, data } = await post(logindata); //需要同步调取 不执行完下面就会执行，让下面的等一等
        if (200 == errno) {
          cookin.set("token", data);
        } else {
          router.replace({ path: "/login", query: { back: path } }); //登录后需要跳回地址
          return;
        }
        //重新发送上次请求
        return instance.request(response.config);
      }
    }
    NProgress.done();
    return data;
  },
  function (error) {
    NProgress.done();
    //对响应错误做些什么
    return Promise.reject(error);
  }
);
//get方法
function get(params) {
  return instance.get(baseURL, { params });
}
//post方法
function post(err, params) {
  // console.log(err);
  return instance.post(baseURL, qs.stringify(err), { params });
}
//富文本
function upload(url, data) {
  return instance.post(url, data);
}

export default {
  get,
  post,
  upload,
  host,
};
